// 蜂窝蜜造平台生成代码，此文件只生成一次，不需要添加到 .beeignore

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fowo.api.datainterface.util.JsonUtil;
import com.fowo.api.entity.Accessories;
import com.fowo.api.entity.BundledProduct;
import com.fowo.api.model.accessories.AccessoriesItemVo;
import com.fowo.api.model.accessories.AccessoriesSearchParamPo;
import com.fowo.api.model.accessories.AccessoriesVo;
import com.fowo.api.model.product.ingredients.ProductIngredientsItemVo;
import com.fowo.api.model.product.ingredients.ProductIngredientsVo;
import com.fowo.api.user.model.JwtUserInfo;
import liquibase.pro.packaged.J;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.*;

/**
 * 辅料管理 服务实现类
 */
@Service

public class AccessoriesServiceImpl extends AccessoriesBaseServiceImpl {

    /**
     * 创建辅料管理
     * @param model 辅料管理
     * @return 新数据的主键
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long create(AccessoriesVo model) throws Exception {
        JwtUserInfo currentUser = JwtUserInfo.fromHeader();
        Accessories entity = new Accessories();
        BeanUtils.copyProperties(model, entity);
        // 设置常量字段
        entity.setType("CP03");
        entity.setCreateTime(new Date());
        entity.setLastUpdateTime(new Date());
        Accessories one = this.getOne(Wrappers.<Accessories>query().lambda().eq(Accessories::getSku, entity.getSku()).eq(Accessories::getType,entity.getType()),false);
        Assert.isNull(one,"sku已存在！");

        if (currentUser != null) {
            entity.setCreateUser(currentUser.getUserId());
            entity.setLastUpdateUser(currentUser.getUserId());
        }
        if (this.save(entity)) {
            model.setId(entity.getId());
            updateAllChilds(model);
            return entity.getId();
        }
        throw new Exception("辅料管理保存失败");
    }


    @SneakyThrows
    @Override
    public Page<AccessoriesItemVo> pageSearch(AccessoriesSearchParamPo search) {
        Page<AccessoriesItemVo> accessoriesItemVoPage = super.pageSearch(search);
        List<AccessoriesItemVo> records = accessoriesItemVoPage.getRecords();
        for (AccessoriesItemVo record : records) {
            AccessoriesVo voById = this.getVoById(record.getId());
            List<ProductIngredientsItemVo> ingredients = voById.getIngredients();
            int num = CollUtil.size(ingredients);
            String body = JsonUtil.getObjectToString(ingredients);

            record.setRelatedProductsNum(num);
            record.setAssociatedProduct(body);
        }
        return accessoriesItemVoPage;
    }

}
